/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "icache.h"
#include "spi.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp_ili9341_4line.h"
#include <stdio.h>
#include <stdlib.h>
#include "wifi.h"
#include "bsp_sht20.h"
#include "cJSON.h"


uint8_t USART5_RxBuff[1024]={0};
volatile uint8_t USART5_RxCounter=0;
uint16_t Sun_data;



// SHT20读取到的温湿度存储变量
float tem = 0;
float hum = 0;

int tem_max = 30;//高于阈值打开空调制冷模式
int tem_min = 25;//低于阈值打开空调制热模式
float hum_max = 66.6;//高于阈值打开风扇

float hum_min = 55;//低于阈值关闭风

char TH[128];
int statu = 1;
int heart  = 66;
int light;
float o2 = 88;
int beep=0;
int mode = 0;//0，用户界面手动模式，1自动模式
char T[32];//屏幕显示温度
char H[32];//屏幕显示湿度
char Heart[32];//屏幕显示心率强度
char O2[32]; //屏幕显示血氧
char FanLD[32];//屏幕显示空调状态
char Mode[32];//显示用户操作模式
char Curtain[32];//显示风扇开关状态
char Pump[32];//显示水泵开关状态
char Beep[32];//显示蜂鸣器状态
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
static void SystemPower_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */
	
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */
	
  /* USER CODE END Init */

  /* Configure the System Power */
  SystemPower_Config();

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_TIM6_Init();
  MX_UART5_Init();
  MX_USART1_UART_Init();
  MX_ICACHE_Init();
  MX_SPI1_Init();
  /* USER CODE BEGIN 2 */
HAL_UARTEx_ReceiveToIdle_IT(&huart5, USART5_RxBuff, 1024);
WIFI_Connect();
HAL_TIM_Base_Start_IT(&htim6);
ILI9341_Init();
ILI9341_Clear(WHITE);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		BSP_SHT20_GetData();
		// 远程控制
		if(tt_flag)
		{
			tt_flag = 0;
			//HAL_UART_Transmit(&huart1, USART5_RxBuff, sizeof(USART5_RxBuff), 1000);
			// 解析JSON数据
			cJSON *root = cJSON_Parse((char *)USART5_RxBuff);
			cJSON *stm32Array = cJSON_GetObjectItem(root, "data");
			cJSON *item = cJSON_GetArrayItem(stm32Array, 0);
			// 空调
			if (cJSON_GetObjectItem(item, "key")->valueint == 105)
			{
				HAL_GPIO_WritePin(GPIOC, GPIO_PIN_6, cJSON_GetObjectItem(item, "value")->valueint);
				if (cJSON_GetObjectItem(item, "value")->valueint)
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_4, 1);
				}
				else
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_4, 0);
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_3, 0);
				}
			}
			// 蜂鸣器
			if (cJSON_GetObjectItem(item, "key")->valueint == 107)
			{
				//打开或关闭蜂鸣器
				HAL_GPIO_WritePin(GPIOA, GPIO_PIN_15, cJSON_GetObjectItem(item, "value")->valueint);
				if (cJSON_GetObjectItem(item, "value")->valueint)
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 1);
				}
				else
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 0);
				}
			}
			
			
			// 喷淋
			if (cJSON_GetObjectItem(item, "key")->valueint == 100)
			{
				//打开或关闭
				if (cJSON_GetObjectItem(item, "value")->valueint)
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 1);
				}
				else
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 0);
				}
			}
			
			
			// 窗帘
			if (cJSON_GetObjectItem(item, "key")->valueint == 201)
			{
				//打开或关闭
				if (cJSON_GetObjectItem(item, "value")->valueint)
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 1);
				}
				else
				{
					HAL_GPIO_WritePin(GPIOC, GPIO_PIN_7, 0);
				}
			}
			
			cJSON_Delete(root);
		}
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI;
  RCC_OscInitStruct.MSIState = RCC_MSI_ON;
  RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_0;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI;
  RCC_OscInitStruct.PLL.PLLMBOOST = RCC_PLLMBOOST_DIV4;
  RCC_OscInitStruct.PLL.PLLM = 3;
  RCC_OscInitStruct.PLL.PLLN = 10;
  RCC_OscInitStruct.PLL.PLLP = 2;
  RCC_OscInitStruct.PLL.PLLQ = 2;
  RCC_OscInitStruct.PLL.PLLR = 1;
  RCC_OscInitStruct.PLL.PLLRGE = RCC_PLLVCIRANGE_1;
  RCC_OscInitStruct.PLL.PLLFRACN = 0;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2
                              |RCC_CLOCKTYPE_PCLK3;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;
  RCC_ClkInitStruct.APB3CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4) != HAL_OK)
  {
    Error_Handler();
  }
}

/**
  * @brief Power Configuration
  * @retval None
  */
static void SystemPower_Config(void)
{

  /*
   * Disable the internal Pull-Up in Dead Battery pins of UCPD peripheral
   */
  HAL_PWREx_DisableUCPDDeadBattery();
/* USER CODE BEGIN PWR */
/* USER CODE END PWR */
}

/* USER CODE BEGIN 4 */

void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	cJSON* root = cJSON_CreateObject();
  cJSON* stm32 = cJSON_CreateArray();
	cJSON_AddItemToObject(root, "stm32", stm32);
	
	//温度 SHT20
	cJSON* temperature = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, temperature);
	cJSON_AddItemToObject(temperature, "key", cJSON_CreateNumber(101));
	cJSON_AddItemToObject(temperature, "name", cJSON_CreateString("temperature"));
	cJSON_AddItemToObject(temperature, "type", cJSON_CreateNumber(3));
	cJSON_AddItemToObject(temperature, "status", cJSON_CreateNumber(0));
	cJSON_AddItemToObject(temperature, "value", cJSON_CreateNumber(tem));
	//湿度 SHT20
	cJSON* humidity = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, humidity);
	cJSON_AddItemToObject(humidity, "key", cJSON_CreateNumber(102));
	cJSON_AddItemToObject(humidity, "name", cJSON_CreateString("humidity"));
	cJSON_AddItemToObject(humidity, "type", cJSON_CreateNumber(3));
	cJSON_AddItemToObject(humidity, "status", cJSON_CreateNumber(0));
	cJSON_AddItemToObject(humidity, "value", cJSON_CreateNumber(hum));
	
	//空调模式--制冷 LED1
	cJSON* AirCondition_Cold = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, AirCondition_Cold);
	cJSON_AddItemToObject(AirCondition_Cold, "key", cJSON_CreateNumber(103));
	cJSON_AddItemToObject(AirCondition_Cold, "name", cJSON_CreateString("ifLD1_ColdOn"));
	cJSON_AddItemToObject(AirCondition_Cold, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(AirCondition_Cold, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_4)));
	cJSON_AddItemToObject(AirCondition_Cold, "value", cJSON_CreateNumber(0));
	
	//空调模式--制热 LED2
	cJSON* AirCondition_Hot = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, AirCondition_Hot);
	cJSON_AddItemToObject(AirCondition_Hot, "key", cJSON_CreateNumber(104));
	cJSON_AddItemToObject(AirCondition_Hot, "name", cJSON_CreateString("ifLD2_HotOn"));
	cJSON_AddItemToObject(AirCondition_Hot, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(AirCondition_Hot, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_3)));
	cJSON_AddItemToObject(AirCondition_Hot, "value", cJSON_CreateNumber(0));
	
  //空调(风扇模拟)
	cJSON* AirCondition = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, AirCondition);
	cJSON_AddItemToObject(AirCondition, "key", cJSON_CreateNumber(105));
	cJSON_AddItemToObject(AirCondition, "name", cJSON_CreateString("ifFan_AirConditionOn"));
	cJSON_AddItemToObject(AirCondition, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(AirCondition, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_6)));
	cJSON_AddItemToObject(AirCondition, "value", cJSON_CreateNumber(0));
	
	//火焰传感器
	cJSON* FireSensor = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, FireSensor);
	cJSON_AddItemToObject(FireSensor, "key", cJSON_CreateNumber(106));
	cJSON_AddItemToObject(FireSensor, "name", cJSON_CreateString("ifFireSensorWarning"));
	cJSON_AddItemToObject(FireSensor, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(FireSensor, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3)));
	cJSON_AddItemToObject(FireSensor, "value", cJSON_CreateNumber(0));
	
	//蜂鸣报警器
	cJSON* BezzerAlarm = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, BezzerAlarm);
	cJSON_AddItemToObject(BezzerAlarm, "key", cJSON_CreateNumber(107));
	cJSON_AddItemToObject(BezzerAlarm, "name", cJSON_CreateString("ifBezzerAlarm"));
	cJSON_AddItemToObject(BezzerAlarm, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(BezzerAlarm, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_15)));
	cJSON_AddItemToObject(BezzerAlarm, "value", cJSON_CreateNumber(0));
	
	//喷淋(震动马达模拟)
	cJSON* Pump = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, Pump);
	cJSON_AddItemToObject(Pump, "key", cJSON_CreateNumber(108));
	cJSON_AddItemToObject(Pump, "name", cJSON_CreateString("ifPumpOn"));
	cJSON_AddItemToObject(Pump, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(Pump, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_7)));
	cJSON_AddItemToObject(Pump, "value", cJSON_CreateNumber(0));
	
	//窗帘LED3模拟
	cJSON* Curtain = cJSON_CreateObject();
	cJSON_AddItemToArray(stm32, Curtain);
	cJSON_AddItemToObject(Curtain, "key", cJSON_CreateNumber(109));
	cJSON_AddItemToObject(Curtain, "name", cJSON_CreateString("ifLD3_CurtainOn"));
	cJSON_AddItemToObject(Curtain, "type", cJSON_CreateNumber(2));
	cJSON_AddItemToObject(Curtain, "status", cJSON_CreateNumber(HAL_GPIO_ReadPin(GPIOC, GPIO_PIN_13)));
	cJSON_AddItemToObject(Curtain, "value", cJSON_CreateNumber(0));
	
	//char *data_json = cJSON_Print(root);
	char *data_json = cJSON_PrintUnformatted(root);
	u1_USART("向采集进程发送数据成功");
	WIFI_SendData(data_json);
	free(data_json);
	cJSON_Delete(root);
	
	if(mode ==1)
	{
		if(tem>=tem_max)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_6,1);
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4,1);
		}
		else if(tem <= tem_min)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_6,1);
			HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_3);
		}
		else if(tem == 27)
		{
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_6,0);
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_3,0);
			HAL_GPIO_WritePin(GPIOC,GPIO_PIN_4,0);
		}
		if(light>500)
		{
				HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,1);
		}
		else if(light <= 300)
		{
				HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,0);
		}
	}
			if(heart <60 || heart > 90||o2 <= 60)//蜂鸣器报警
			{
				beep =1;
				if(beep == 1)
					HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,1);
				HAL_UART_Transmit(&huart5,"心率/血氧异常",15,100);
				strcpy(Beep,"beep:ON");
			}
			else 
			{
				beep=0;
			  HAL_GPIO_WritePin(GPIOC,GPIO_PIN_13,0);
			}	
}
void HAL_GPIO_EXTI_Falling_Callback(uint16_t GPIO_Pin)
{
	HAL_GPIO_TogglePin(GPIOC,GPIO_PIN_7);
	if(HAL_GPIO_ReadPin(GPIOC,GPIO_PIN_7)==1)
	{
		strcpy(Pump,"Pump:ON");
	}
	else strcpy(Pump,"Pump:OFF");
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
